package testJdk.commonUse.collections.lambda;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author keyer
 * @Description : 描述
 * Created by cyd on 2021-03-30 15:48:22
 */
public class Test02 {

    public static void main(String[] args) {
        List<Apple> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Apple apple = new Apple();
            apple.setName("苹果" + (10 - i));
            apple.setWeight("重量" + i);
            apple.setColor("颜色" + i);
            list.add(apple);
        }
        list.add(new Apple("苹果10"));
        System.out.println("------------------原本的顺序----------------------");
        list.forEach(apple -> {
            System.out.println(apple.getName() + "---" + apple);
        });
        System.out.println("------------------根据name排序后的list----------------------");
        List<Apple> apples = list.stream().sorted(Comparator.comparing(Apple::getName)).collect(Collectors.toList());
        System.out.println(apples);


        System.out.println("------------------转成hashmap会自然排序----------------------");
        Map<String, List<Apple>> map1 = apples.stream().collect(Collectors.groupingBy(Apple::getName));
        map1.entrySet().forEach(a -> {
            System.out.println(a.getKey() + "-----" + a.getValue());
        });
        System.out.println("------------------直接输出map----------------------");
        System.out.println(map1);


        System.out.println("------------------用LinkedHashMap恢复原本顺序----------------------");
        // 名字相同的会被分为List
        LinkedHashMap<String, List<Apple>> map = list.stream().collect(Collectors.groupingBy(Apple::getName, LinkedHashMap::new, Collectors.toList()));
        map.entrySet().forEach(a -> {
            System.out.println(a.getKey() + "-----" + a.getValue());
        });
    }
}
